import React, { useEffect, useState } from 'react'
import { IAppMenuItem } from '../api/interface/kubeflowInterface'
import { getParam } from '../util'
import { Spin } from 'antd'
import { useLocation } from 'react-router-dom'
import { flowiseAuthManager } from '../utils/flowiseAuth'

export default function IframeTemplate(props?: IAppMenuItem) {
    const location = useLocation()
    const [url, setUrl] = useState('')
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        // 强制重置状态
        setUrl('')
        setLoading(true)

        // 优先使用props中的url，如果没有再从URL参数获取
        const targetUrl = props?.url || getParam('url') || ''
        console.log('=== IframeTemplate Debug Info ===')
        console.log('Props URL:', props?.url)
        console.log('Param URL:', getParam('url'))
        console.log('Target URL:', targetUrl)
        console.log('Current location:', location.pathname)
        console.log('Props object:', props)
        console.log('=================================')

        if (targetUrl) {
            // 延迟设置URL，确保状态完全重置
            setTimeout(() => {
                setUrl(targetUrl)
            }, 10)

            if (targetUrl.includes('flowise') || targetUrl.includes('3000')) {
                console.log('=== Flowise认证集成开始 ===')

                // 使用认证管理器处理认证
                const sendAuthInfo = () => {
                    flowiseAuthManager.sendAuthInfo()
                }

                // 延迟发送认证信息，确保iframe完全加载
                setTimeout(sendAuthInfo, 1000)
                setTimeout(sendAuthInfo, 2000)
                setTimeout(sendAuthInfo, 3000)

                console.log('=== Flowise认证集成设置完成 ===')
            }
        } else {
            console.error('No URL found in props or params')
        }
    }, [props?.url, location.pathname, JSON.stringify(props)]) // 添加 JSON.stringify(props) 确保 props 变化时重新执行

    const handleIframeLoad = () => {
        setLoading(false)
    }

    return (
        <>
            {loading && <div className="d-f jc ac" style={{ position: 'absolute', width: '100%', height: '100%', zIndex: 10 }}>
                <Spin size="large" tip="加载中..." />
            </div>}
            {url && (
                <iframe
                    key={`${url}-${location.pathname}`} // 使用更唯一的key，确保路由变化时iframe重新加载
                    id="_frontendAppCustomFrame_"
                    src={url}
                    allowFullScreen
                    allow="microphone;camera;midi;encrypted-media;"
                    className="w100 h100 fade-in"
                    style={{ border: 0, display: 'block' }}
                    onLoad={handleIframeLoad}
                >
                </iframe>
            )}
            {!url && (
                <div className="d-f jc ac h100">
                    <div>No URL configured</div>
                </div>
            )}
        </>
    )
}
